package com.itheima.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;

/*
    统一字符集过滤器
    解决post提交中文乱码问题,tomcat8.5以后,get字符集统一有服务器实现
    tomcat9只需要实现doFilter
    tomcat8三个方法都需要实现
 */
@WebFilter(value = "/*",initParams = {@WebInitParam(name="encoding",value = "UTF-8")})
public class EncodingFilter implements Filter {
    private String encoding;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        encoding=filterConfig.getInitParameter("encoding");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //request和response字符集统一设置即可
        servletRequest.setCharacterEncoding(encoding);
        servletResponse.setContentType("text/html;charset="+encoding);
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
